document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    const loginError = document.getElementById('loginError');
    const registerError = document.getElementById('registerError');
    const toggleBtns = document.querySelectorAll('.toggle-btn');

    // 表单切换功能
    toggleBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const targetForm = this.getAttribute('data-form');
            
            // 更新按钮状态
            toggleBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 切换表单显示
            document.querySelectorAll('.auth-form').forEach(form => {
                form.classList.remove('active');
            });
            if (targetForm === 'login') {
                loginForm.classList.add('active');
            } else {
                registerForm.classList.add('active');
            }
            
            // 清除错误信息
            loginError.textContent = '';
            registerError.textContent = '';
        });
    });

    // 登录表单处理
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        // 发送登录请求
        fetch(`http://localhost:8080/auth/login/student?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                // 登录成功
                loginError.textContent = '';
                // 存储登录状态和用户信息
                sessionStorage.setItem('isLoggedIn', 'true');
                sessionStorage.setItem('username', data.data.username);
                sessionStorage.setItem('studentId', data.data.studentId);
                // 跳转到主页
                window.location.href = 'dashboard.html';
            } else {
                // 登录失败
                loginError.textContent = data.message || '登录失败';
                // 清空密码输入框
                document.getElementById('password').value = '';
            }
        })
        .catch(error => {
            loginError.textContent = '网络错误，请稍后重试';
            console.error('Error:', error);
        });
    });

    // 注册表单处理
    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const username = document.getElementById('regUsername').value;
        const email = document.getElementById('regEmail').value;
        const password = document.getElementById('regPassword').value;
        const confirmPassword = document.getElementById('regConfirmPassword').value;

        // 验证密码匹配
        if (password !== confirmPassword) {
            registerError.textContent = '两次输入的密码不一致';
            return;
        }

        // 验证密码强度
        if (password.length < 6) {
            registerError.textContent = '密码长度至少为6个字符';
            return;
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            registerError.textContent = '请输入有效的邮箱地址';
            return;
        }

        // 发送注册请求
        fetch('http://localhost:8080/auth/register/student', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password,
                email: email
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                // 注册成功
                registerError.textContent = '';
                alert('注册成功！请使用新账号登录。');
                // 清空表单并切换到登录页面
                registerForm.reset();
                document.querySelector('[data-form="login"]').click();
            } else {
                // 注册失败
                registerError.textContent = data.message || '注册失败';
            }
        })
        .catch(error => {
            registerError.textContent = '网络错误，请稍后重试';
            console.error('Error:', error);
        });
    });

    // 检查是否已登录
    if (sessionStorage.getItem('isLoggedIn') === 'true') {
        window.location.href = 'dashboard.html';
    }

    // 创建浮动图标动画
    createFloatingIcons();
});

// 创建浮动图标
function createFloatingIcons() {
    const icons = document.querySelectorAll('.floating-servers i');
    icons.forEach(icon => {
        setRandomPosition(icon);
        setInterval(() => {
            setRandomPosition(icon);
        }, 15000);
    });
}

// 设置随机位置
function setRandomPosition(element) {
    const x = Math.random() * 80 + 10; // 10% to 90%
    const y = Math.random() * 80 + 10; // 10% to 90%
    element.style.transition = 'all 15s ease';
    element.style.left = `${x}%`;
    element.style.top = `${y}%`;
} 